/**
 * Project SearchEngine
 */


#include "WebPage.h"
#include "Configuration.h"
#include "WordSegmentation.h"
#include <unordered_map>
#include <string>

using std::unordered_map;
using std::stoi;

WebPage::WebPage(string& doc, WordSegmentation& jieba)
: _doc(doc)
{
    //获取停用词集
    
  /* cout << "WebPage::" <<  _doc << endl; */  
    _docId =stoi( processDoc(_doc, "<docid>", "</docid>"));//有类型转换string--->int
    _docTitle = processDoc(_doc, "<title>", "</title>");
    _docLink = processDoc(_doc, "<link>", "</link>");

    string content = processDoc(_doc, "<content>", "</content>");
    string description = processDoc(_doc, "<description>", "</desctrption>");
    if (content.size() > 500) {
        _docContent = content;
    }
    else {
        _docSummary = content;
    }
    if (description.size() > 500) {
        _docContent = description;
    }
    else {
        _docSummary = description;
    }



    cout << "title: " << _docTitle << endl;
}
WebPage::~WebPage()
{
    
}

int WebPage::getDocId()
{
    return _docId;
}

string WebPage::getDoc()
{

}

map<string,int>& WebPage::getWordsMap()
{
    
}

//识别<docid>,返回其所在位置
//len是要查找子串的长度

int minWindow(string str, string& pattern, int len) //str引用报错
{
    string tmp;
    int left = 0;
    int end = (int)str.size() - len;

    while (left < end) {

        //从left开始的size个字节
        tmp = str.substr(left, len);
        if (tmp == pattern) {
            /* cout << endl << left + len << endl; */
            return left + len;
        }
        else {
            left++;
        }
    }
    //没有找到
    return -1;
}

/* void WebPage::processDoc(const string& doc, Configuration& config, */
/*                          WordSegmentation& jieba) */
string WebPage::processDoc(const string& doc, string patternA, string patternB)
{
    string tmp = doc;
    int len = patternA.size();
    int begin = 0;
    int end = 0;

    begin = minWindow(tmp, patternA, len);
    //对字符串做了截取---后面的end是从截取后的位置开始跑的
    tmp = doc.substr(begin, doc.size());
    end = minWindow(tmp, patternB, len + 1 ); //--使用的len + 1;
    if (-1 == begin || -1 == end) {
        cout << "processDoc error!" << endl;
    }

    int count = end - patternB.size();
    string answer = doc.substr(begin, count);

    return answer;

    
}
